package com.heima.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.client.article.IArticleClient;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserRelationDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApAuthor;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.model.common.pojos.user.ApUserFan;
import com.heima.model.common.pojos.user.ApUserFollow;
import com.heima.user.mapper.ApUserFansMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserFollowService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private ApUserFansMapper apUserFansMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户关注行为
     *
     * @param userRelationDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult userFollow(UserRelationDto userRelationDto) {
        //验证数据
        if (userRelationDto == null || userRelationDto.getArticleId() == null || userRelationDto.getAuthorId() == null) {
            //都为null，则数据不合法
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //将行为状态写到redis里面
        saveInRedis(userRelationDto);
        Integer currentId = ApThreadLocalUtil.get();

        //登录用户userid不存在
        if (currentId == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据用户id和作者id分别查询出对应的信息
        //远程调用根据作者id查询信息
        ResponseResult result = articleClient.getUserInfo(userRelationDto.getAuthorId());
        if (result.getCode() != 200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApAuthor apAuthor = JSONObject.parseObject(JSON.toJSONString(result.getData()), ApAuthor.class);
        ApUser followApUser = apUserMapper.selectById(currentId);

        followOrCancel(userRelationDto, apAuthor, followApUser);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 将关注状态写到redis中
     *
     * @param userRelationDto
     */
    private void saveInRedis(UserRelationDto userRelationDto) {
        //设置key
        String key = "ATTENTION_" + userRelationDto.getAuthorId();
        redisTemplate.opsForValue().set(key, String.valueOf(userRelationDto.getOperation()));
    }

    /**
     * 取消或者关注
     *
     * @param userRelationDto
     * @param apAuthor
     * @param followApUser
     */
    private void followOrCancel(UserRelationDto userRelationDto, ApAuthor apAuthor, ApUser followApUser) {
        if (userRelationDto.getOperation() == 0) {
            //关注
            //用户关注作者，操作ap_user_follow表
            //构建Ap_user_follow实体类
            ApUserFollow apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(followApUser.getId());
            apUserFollow.setFollowId(apAuthor.getUserId());
            apUserFollow.setFollowName(apAuthor.getName());
            apUserFollow.setCreatedTime(new Date());
            save(apUserFollow);
            //作者关联用户，操作ap_user_fan表
            ApUserFan apUserFan = new ApUserFan();
            apUserFan.setUserId(apAuthor.getUserId());
            apUserFan.setFansId(followApUser.getId());
            apUserFan.setFansName(followApUser.getName());
            apUserFan.setCreatedTime(new Date());
            apUserFan.setIsDisplay((short) 1);
            apUserFan.setIsShieldLetter((short) 0);
            apUserFan.setIsShieldComment((short) 0);
            apUserFansMapper.insert(apUserFan);
        } else if (userRelationDto.getOperation() == 1) {
            //取消关注
            //删除表中的信息Ap_user_follow和ap_user_fan
            LambdaQueryWrapper<ApUserFollow> eq = Wrappers.lambdaQuery(ApUserFollow.class)
                    .eq(ApUserFollow::getUserId, followApUser.getId())
                    .eq(ApUserFollow::getFollowId, apAuthor.getUserId());
            remove(eq);

            apUserFansMapper.delete(new QueryWrapper<ApUserFan>()
                    .eq("user_id", apAuthor.getUserId())
                    .eq("fans_id", followApUser.getId()));
        }
    }
}
